package com.mifan.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mifan.common.Results;
import com.mifan.entity.HmDetail;
import com.mifan.mapper.HmDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 游资每日交易明细表 前端控制器
 * </p>
 *
 * @author Milan
 * @since 2024-09-27
 */
@RestController
@RequestMapping("/hm_detail")
public class HmDetailController {


    @Resource
    private HmDetailMapper hmDetailMapper;

    @Resource
    private RestTemplate restTemplate;


    /**
     * 从 Tushare API 加载数据
     * @param tradeDate
     * @return
     */
    @GetMapping("/loadTushareData")
    public Results insertByTushare(@RequestParam  String tradeDate) {
        // 查看数据库里面有没有 当前时间的数据
        QueryWrapper<HmDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trade_date", tradeDate).last("LIMIT 1");
        HmDetail selectOne = hmDetailMapper.selectOne(queryWrapper);
        if (selectOne != null) {
            return Results.success("数据已存在", null);
        }
        String url = "https://api.tushare.pro"; // 替换为实际的 Tushare API 端点
        String apiKey = "320aafac764e1b980c618bc7bf2f6464a11a2d2386567838e0ffc026"; // 替换为你的 Tushare API 密钥
        // Set up headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // Set up headers
        String requestBody = "{ \"api_name\": \"hm_detail\", \"token\": \"" + apiKey + "\", \"params\": {\"trade_date\": "+tradeDate+"} }";
        // Create the HttpEntity
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        // Make the POST request
        String response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();

        List<HmDetail> hmDetails = parseResponse(response);
        // 插入数据库
        for (HmDetail hmDetail : hmDetails) {
            hmDetailMapper.insert(hmDetail);
        }
        return Results.success(null);
    }



    /**
     * 查询游资每日交易明细
     *
     * @param tradeDate 交易日期
     * @return 游资每日交易明细列表
     */
    @GetMapping("/list")
    public Results list(@RequestParam String tradeDate,
                        @RequestParam String hmName,
                        @RequestParam String tsCode,
                        @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer size
    ) {
        PageHelper.startPage(page,size);
        QueryWrapper<HmDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trade_date", tradeDate);
        if (hmName != null && !hmName.isEmpty()) {
            queryWrapper.eq("hm_name", hmName);
        }
        if (tsCode != null && !tsCode.isEmpty()) {
            queryWrapper.eq("ts_code", tsCode);
        }
        queryWrapper.orderByAsc("sell_amount");
        List<HmDetail> hmDetails = hmDetailMapper.selectList(queryWrapper);
        PageInfo pageInfo = new PageInfo(hmDetails);
        return Results.success(pageInfo);
    }

    /**
     * 解析 Tushare API 响应
     *
     * @param response Tushare API 响应
     * @return HmDetail 对象列表
     */
    private List<HmDetail> parseResponse(String response) {
        List<HmDetail> hmDetails = new ArrayList<>();
        // 解析 JSON 响应并转换为 HmDetail 对象列表
        // 根据实际响应格式实现解析逻辑
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response);
            JsonNode dataNode = rootNode.path("data").path("items");
            if (dataNode.isArray()) {
                for (JsonNode node : dataNode) {
                    HmDetail detail = new HmDetail();
                    detail.setTradeDate(node.get(0).asText());
                    detail.setTsCode(node.get(1).asText());
                    detail.setTsName(node.get(2).asText());
                    detail.setBuyAmount(new BigDecimal(node.get(3).asText()).setScale(2, RoundingMode.HALF_UP));
                    detail.setSellAmount(new BigDecimal(node.get(4).asText()).setScale(2, RoundingMode.HALF_UP));
                    detail.setNetAmount(new BigDecimal(node.get(5).asText()).setScale(2, RoundingMode.HALF_UP));
                    detail.setHmName(node.get(6).asText());
                    detail.setHmOrgs(node.get(7).asText());
                    hmDetails.add(detail);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return hmDetails;
    }
}
